# coding: utf-8

"""Format translation between data set in formats. Intend to do this,
there needs a middle-format at first that all formats can co-translate
with it. This module will expose a common interface, accept a data
parameter and 2 format parameters as arguments, and do the translation.

As the middle-format, dictionaries will be used.

Write by TONE (wick.zt@gmail.com) at 2016/05/08

Supported:
    - dictionaries
    - CSV
    - excel
    - JSONLines
"""

from functools import reduce

# import openpyxl as xls


def translate(data, _from, _to):
    pass

def _sort(data, key=None):
    """Sort the middle-format data by key to prettify the output.
    Params:
        - data
        - key: list, function or None
            if None, will return the raw input as output
            accept a list of fields to specify the order
            accept a function to calculate the keys
    Return:
        - sorted data
    """
    pass


# CSV

def _from_csv(header, *rows):
    """In memory, CSV data is a table, i.e. a matrix, a list of list.
    Just use this function like:
        >>> middle = _from_csv(*csv_table)
    So that the csv_table must has a header.
    """
    return [dict(zip(header, row)) for row in rows]

def _to_csv(data, fields={}, null=''):
    """Accept data as dictionaries and return a CSV table.
    Params:
        - data: a list of dict
        - fields: field name dict like {'name': '姓名', 'age': '年龄'}
        - null: padding when missing the key
    Return:
        - csv_table
    """
    _getrow = lambda d, keys: [d.get(k, null) for k in keys]
    if fields:
        header = fields.values()
        keys = fields.keys()
    else:
        header = list(reduce(set.union,
                             (d.keys() for d in data),
                             set()))
        keys = header.copy()
    return [header] + [_getrow(d, list(keys)) for d in data]


# Excel

def _from_excel():
    pass

def _to_excel():
    pass


# JSONLines

def _from_jsonlines():
    pass

def _to_jsonlines():
    pass
